package org.leiyang.netty.listener;

import io.netty.channel.ChannelHandlerContext;
import org.leiyang.common.dtos.Message;
import org.leiyang.common.dtos.MessageType;
import org.leiyang.common.dtos.R;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * 消息(文本类，音视频类)处理
 */
@Component
@Order(2)
public class MsgReceivedFilter implements INettyMsgFilter {

    @Override
    public Mono<Boolean> chain(Message message, ChannelHandlerContext ctx, String serverIp, String port, Boolean httpFormat) {
        if(message.getMessageType() == MessageType.MSG_TEXT ||
                message.getMessageType() == MessageType.MSG_VIDEO ||
                message.getMessageType() == MessageType.MSG_AUDIO) {
            //直接将Message发送给客户端
            sendResponse(ctx, R.ok(message), channelHandlerContext -> {}, httpFormat);
            return Mono.just(false);
        }
        return Mono.just(true);
    }

    /**
     * 发送响应给客户端
     * @param ctx ctx
     * @param reps 响应数据
     */
//    private void sendResponse(ChannelHandlerContext ctx, R<?> reps) {
//        // 构建响应内容
//        byte[] content = JSON.toJSONString(reps).getBytes(CharsetUtil.UTF_8);
//        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
//        response.content().writeBytes(content);
//        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
//        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
//        // 发送响应
//        ctx.writeAndFlush(response).addListener(future -> {
//            if (future.isSuccess()) {
//                logger.info("Msg Server端已发送消息到客户端: {}", reps.getData());
//            }
//        });
//    }
}
